package com.ict.bills.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.ict.bills.domain.User;
import com.ict.bills.service.UserService;
import com.ict.bills.utils.ResultObj;
import com.ict.bills.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Lizbeth9421
 * @Date: 2021/10/10/14:59
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping({"/toLogin", "/"})
    public String toLogin() {
        return "login";
    }

    /**
     * 验证码
     *
     * @param resp
     */
    @GetMapping("/getCode")
    public void getCode(final HttpServletResponse resp) {
        //定义图像验证码的长、宽、验证码字符数、干扰线宽度
        final ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(116, 36, 4, 2);
        //把验证码信息设置到session
        WebUtils.getHttpSession().setAttribute("CODE_IN_SESSION", captcha.getCode());
        //将验证码输出到页面
        try {
            captcha.write(resp.getOutputStream());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查登录
     *
     * @param loginname 登录名
     * @param password 密码
     * @param code 验证码
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public ResultObj login(String loginname, String password, String code) {
        String sessionCode = (String) WebUtils.getHttpSession().getAttribute("CODE_IN_SESSION");
        if (code != null && code.equalsIgnoreCase(sessionCode)) {
            User user = userService.checkLogin(loginname, password);
            if (user != null) {
                WebUtils.getHttpSession().setAttribute("USER_IN_SESSION", user);
                return new ResultObj(200, "登录成功");
            } else {
                return new ResultObj(-1, "账号或密码错误！");
            }
        } else {
            return new ResultObj(-1, "验证码错误！");
        }
    }


}
